<template>
  <div class="city">
    <van-nav-bar title="城市列表" fixed z-index="2">
      <template #left>
        <van-icon name="cross" class="iconFont" @click="$router.back()" />
      </template>
    </van-nav-bar>

    <van-index-bar :index-list="indexList" sticky :sticky-offset-top="46">
      <!-- 当前城市 -->
      <van-index-anchor index="#">当前城市</van-index-anchor>
      <van-cell title="上海" />
      <!-- ！当前城市 -->

      <!-- 热门城市 -->
      <van-index-anchor index="热">热门城市</van-index-anchor>
      <van-cell
        :title="item.label"
        v-for="(item, index) in hotcitysInfo"
        :key="index"
        @click="hotCtiy(item)"
      />
      <!-- 每一项 -->
      <div class="box" v-for="item in indexList" :key="item">
        <van-index-anchor :index="item" />
        <van-cell
          :title="item.label"
          v-for="item in allCityList[item]"
          :key="item.label"
          @click="getCity(item)"
        />
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import { hotCity, allCitys } from '@/api/city.js'
export default {
  name: 'city',
  data () {
    return {
      indexList: ['#', '热'],
      hotcitysInfo: [],
      allCityList: [],
      // newIndexList: []
      new: {}
    }
  },

  created () {
    this.hotcitys()
    this.getall()
  },

  methods: {
    // 热搜城市
    async hotcitys () {
      const res = await hotCity()
      this.hotcitysInfo = res
    },

    // 全部城市
    async getall () {
      const res = await allCitys(1)
      // 索引
      const index = res.map((item) => {
        return item.short[0].toUpperCase()
      })
      // this.newIndexList = [...(new Set(index.sort()))]
      this.indexList.push(...new Set(index.sort()))

      // 城市
      // 让每一项key为为short首字母大写 并让A改为数组
      res.map((item) => {
        this.allCityList[item.short[0].toUpperCase()] = []
      })

      // 再在allCityList的key为ABC的那一项添加内容
      res.map((item) => {
        this.allCityList[item.short[0].toUpperCase()].push(item)
      })
    },
    // 点击跳转到该城市
    hotCtiy (item) {
      console.log(item)
      this.$store.commit('infoSetStorage2', item)
      this.$router.back()
    },
    getCity (item) {
      console.log(item)
      this.$store.commit('infoSetStorage2', item)
      this.$router.push('/layout/home')
    }
  }
}
</script>

<style scoped lang="less">
.van-nav-bar {
  background-color: #21b97a;
  .iconFont {
    color: #fff;
    font-size: 18px;
  }
  /deep/.van-nav-bar__title {
    font-size: 18px;
    color: #fff;
  }
}
.van-index-bar {
  margin-top: 46px;
}
/deep/.van-index-bar__sidebar {
  padding-top: 20px;
  height: 85%;
}
/deep/.van-index-bar__index {
  flex: 1;
  font-size: 15px;
  font-weight: 400;
}
/deep/.van-cell {
  height: 50px;
  font-size: 16px;
}
/deep/.van-index-anchor {
  font-size: 14px;
  padding: 10px 15px;
  color: #999;
}
/deep/.van-index-bar__index--active {
  color: #21b97a;
}
</style>
